//
//  SEGNewSelectCommunityViewModel.m
//  SEGViewModel
//
//  Created by 乔杨 on 2020/6/15.
//

#import "SEGNewSelectCommunityViewModel.h"

@interface SEGNewSelectCommunityViewModel ()


@end

@implementation SEGNewSelectCommunityViewModel

- (instancetype)init {
    self = [super init];
    if (self) {
        [self seg_createSearchHistorySignal];
        [self seg_createRegisterCommand];
        [self seg_createHotCommunitySignal];
        [self seg_createCityListSignal];
        [self seg_createChangeCommunitySignal];
        [self seg_createSearchCommunitySignal];
        [self seg_createSaveHistorySignal];
        [self seg_createDeleteCommunityCommand];
        [self seg_createNoSearchResultCommand];
    }
    return self;
}
- (void)seg_createSearchHistorySignal {
    @weakify(self);
    self.searchHistorySignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        // 获取我的搜索历史
        [self.requestManager requestFindMyCommunityFinished:^(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage) {
            if (isSuccessed) {
                self.historyArray = self.requestManager.dataSourceCommunityList;
                [subscriber sendNext:@""];
                [subscriber sendCompleted];
            } else {
                NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                [subscriber sendError:error];
            }
        }];
        
        return nil;
    }];
}
- (void)seg_createRegisterCommand {
    @weakify(self);
    self.registerCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(RACTuple *tuple) {
        RACTupleUnpack(NSString *communityId, NSString *communityName, NSString *tel, NSString *code, NSString *pwd, NSString *randomToken) = tuple;
        // 注册（调用注册接口时）  RG    小区id、小区名称
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.requestManager requestUserAppRegisterByTel:tel smsCode:code password:pwd communityId:ValueToString(communityId) randomToken:randomToken Finished:^(BOOL isSuccessed, id result, NSString* codeType, NSString* errorMessage) {
                if (isSuccessed) {
                    [SEGLoginV2Manager segSaveUserTelToLocal:tel];
                    [SEGLoginV2Manager segSaveUserPasswordToLocal:pwd];
                    [subscriber sendNext:@""];
                    [subscriber sendCompleted];
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            
            return nil;
        }];
    }];
}
- (void)seg_createHotCommunitySignal {
    @weakify(self);
    self.hotCommunitySignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [self.requestManager requestQueryCommunityListWithCityCode:self.cityCode finished:^(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage) {
            if (isSuccessed) {
                self.hotCommunityArray = self.requestManager.hotCommunityList;
                // 设置热门社区数据源
                NSMutableArray *tempArray = [NSMutableArray array];
                [self.hotCommunityArray enumerateObjectsUsingBlock:^(SEGChangeCommunityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [tempArray addObject:obj.communityName];
                }];
                self.tagsArray = tempArray;
                [subscriber sendNext:@""];
                [subscriber sendCompleted];
            } else {
                NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                [subscriber sendError:error];
            }
        }];
        
        return nil;
    }];
}
- (void)seg_createCityListSignal {
    @weakify(self);
    self.cityListSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [self.requestManager requestQueryCityListWithCity:^(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage) {
            [subscriber sendNext:self.requestManager.cityList];
            [subscriber sendCompleted];
        }];
        return nil;
    }];
}
- (void)seg_createChangeCommunitySignal {
    @weakify(self);
    self.changeCommunitySignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [self.requestManager requestswitchCommunityBycommunityId:self.communityId Finished:^(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage) {
            if (!isSuccessed) {
                NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedFailureReasonErrorKey:@"服务器忙，请重新操作"}];
                [subscriber sendError:error];
                return;
            }
            
            [[SEGProfileManager sharedManager] requestProfilecompleted:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    // 业主逻辑：只调用Profile
                    [subscriber sendNext:@""];
                    [subscriber sendCompleted];
                    return;
                } else {
                    NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedFailureReasonErrorKey:@"服务器忙，请重新操作"}];
                    [subscriber sendError:error];
                }
            }];
        }];
        return nil;
    }];
}
- (void)seg_createSearchCommunitySignal {
    @weakify(self);
    self.searchCommunityCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *communityName) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.requestManager requestFindCommunityByName:communityName cityCode:self.cityCode Finished:^(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage) {
                if (isSuccessed) {
                    self.searchCommunityArray = self.requestManager.dataSourceCommunity;
                    [subscriber sendNext:@(self.searchCommunityArray.count)];
                    [subscriber sendCompleted];
                } else {
                    NSInteger errorCode = 2;
                    if (self.cityCode && self.cityCode.length > 0) errorCode = 1;
                    NSError *error = [NSError errorWithDomain:@"" code:errorCode userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            
            return nil;
        }];
    }];
}
- (void)seg_createSaveHistorySignal {
    @weakify(self);
    self.saveHistorySignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [self.requestManager requestSaveRegisterCommunityBycommunityId:self.communityId Finished:^(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage) {
            if (isSuccessed) {
                [subscriber sendNext:@""];
                [subscriber sendCompleted];
            } else {
                 NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                 [subscriber sendError:error];
            }
        }];
        
        return nil;
    }];
}
- (void)seg_createDeleteCommunityCommand {
    @weakify(self);
    self.deleteCommunityCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(NSString *communityId) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.requestManager requestDeleteCommunityBycommunityId:communityId Finished:^(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage) {
                if (isSuccessed) {
                    [subscriber sendNext:@""];
                    [subscriber sendCompleted];
                } else {
                   NSError *error = [NSError errorWithDomain:@"" code:codeType.integerValue userInfo:@{NSLocalizedFailureReasonErrorKey:errorMessage}];
                   [subscriber sendError:error];
                }
            }];
            return nil;
        }];
    }];
}
- (void)seg_createNoSearchResultCommand {
    self.noSearchResultCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(RACTuple *tuple ) {
        RACTupleUnpack(NSNumber *isFromLogin, NSString *searchContent) = tuple;
        // 添加到历史记录
        self.communityId = @"1";
        self.communityName = @"童话镇";
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            if (isFromLogin.boolValue) {
                [[NSUserDefaults standardUserDefaults] setObject:searchContent forKey:kSumbitSearchCommunityAdvice];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [subscriber sendNext:@""];
                [subscriber sendCompleted];
            } else {
                // 将记录用户搜索框内输入的关键词，系统生成一条用户“搜索不到xxxxx”用户反馈记录，显示在后台；
                [[SEGSuggestsaveManager sharedManager] requestSuggestsaveWithContext:searchContent sugType:@"1001" finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                     [subscriber sendNext:@""];
                     [subscriber sendCompleted];
                }];
            }
            
            return nil;
        }];
    }];
}

#pragma mark - Getter
- (SEGRequestManager *)requestManager {
    if (!_requestManager) _requestManager = [[SEGRequestManager alloc] init];
    return _requestManager;
}

@end
